package com.dsteiner.xelavos.server;

import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dsteiner.widgets.client.StringUtil;
import com.dsteiner.widgets.client.domain.ModelObject;
import com.dsteiner.widgets.client.domain.Sort;
import com.dsteiner.widgets.client.rpc.SearchRequest;
import com.dsteiner.widgets.client.rpc.SearchRequest.SearchRequestImpl;
import com.dsteiner.xelavos.client.domain.Job;
import com.dsteiner.xelavos.client.domain.Leisure;
import com.dsteiner.xelavos.client.domain.Product;
import com.dsteiner.xelavos.client.domain.Service;
import com.dsteiner.xelavos.client.domain.User;
import com.dsteiner.xelavos.server.dao.DataDao;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;

public class ReportServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(ReportServlet.class.getName());
	private DataDao dataDao = DataDao.dataDao;
	private Queue mailQueue = QueueFactory.getQueue("mail-queue");
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			SearchRequestImpl newItemsRequest = new SearchRequestImpl();
			newItemsRequest.setType(SearchRequest.TYPE_ALL);
			newItemsRequest.setOffset(0);
			newItemsRequest.setLimit(10);
			newItemsRequest.setSort(new Sort("registeredDate", false));
			
			StringBuffer plainTextSb = new StringBuffer();
			StringBuffer htmlTextSb = new StringBuffer();
			
			newItemsRequest.setClassName(Product.class.getName());
			List newProducts = DataDao.dataDao.search(newItemsRequest).getObjects();
			if(newProducts != null && !newProducts.isEmpty()){
				addSubTitle("Nuevos productos:", plainTextSb, htmlTextSb);
				formatModelObjects(newProducts, plainTextSb, htmlTextSb);
			}
			
			newItemsRequest.setClassName(Service.class.getName());
			List newServices = DataDao.dataDao.search(newItemsRequest).getObjects();
			if(newServices != null && !newServices.isEmpty()){
				addSubTitle("Nuevos servicios:", plainTextSb, htmlTextSb);
				formatModelObjects(newServices, plainTextSb, htmlTextSb);
			}
			
			newItemsRequest.setClassName(Job.class.getName());
			List newJobs = DataDao.dataDao.search(newItemsRequest).getObjects();
			if(newJobs != null && !newJobs.isEmpty()){
				addSubTitle("Nuevos trabajos:", plainTextSb, htmlTextSb);
				formatModelObjects(newJobs, plainTextSb, htmlTextSb);
			}
			
			newItemsRequest.setClassName(Leisure.class.getName());
			List newLeisures = DataDao.dataDao.search(newItemsRequest).getObjects();
			if(newLeisures != null && !newLeisures.isEmpty()){
				addSubTitle("Nuevas recreaciones:", plainTextSb, htmlTextSb);
				formatModelObjects(newLeisures, plainTextSb, htmlTextSb);
			}
			
			String greetingsText = "Eso son algunos nuevos registros en Xelavos.com\n\n ";
			plainTextSb.insert(0, greetingsText);
			htmlTextSb.insert(0, StringUtil.toHtml(greetingsText));
			String subject = "Su reporte semanal de XelaVos.com";
			log.info(plainTextSb.toString());
			log.info(htmlTextSb.toString());
			
			List<String> userIds = dataDao.getObjectIds(User.class);
			for (String userId : userIds) {
				String cancelWeeklyReportUrl = "http://www.xelavos.com/xelavos/emailAdmin?cancelWeeklyReport=true"
					+"&uid="+userId;
				String htmlTextId = UUID.randomUUID().toString();
				EmailServlet.htmlTextMap.put(htmlTextId, htmlTextSb.toString()
						+"<br>para ya no recibir correos semanales <a href=\""+cancelWeeklyReportUrl+"\">haga click en ese link</a>");
				String plainTextId = UUID.randomUUID().toString();
				EmailServlet.plainTextMap.put(plainTextId, plainTextSb.toString()
						+"\npara ya no recibir correos semanales visite el siguiente link\n"+cancelWeeklyReportUrl);
				mailQueue.add(url("/tasks/email")
						.param("checkReceiveReport", "true")
						.param("userId", userId)
						.param("htmlTextId", htmlTextId)
						.param("plainTextId", plainTextId)
						.param("subject", subject));
			}
		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}

	private void addSubTitle(String message, StringBuffer plainTextSb, StringBuffer htmlTextSb) {
		plainTextSb.append(message).append("\n\n");
		htmlTextSb.append("<span style=\"font-weight:bold;font-size:16px;text-decoration:underline;\">")
		.append(message).append("</span><br><br>");
	}

	private void formatModelObjects(List<ModelObject> items, StringBuffer plainTextSb, StringBuffer htmlTextSb) {
		Calendar oneWeekAgo = Calendar.getInstance();
		oneWeekAgo.add(Calendar.DAY_OF_MONTH, -7);
		for (ModelObject modelObject : items) {
			if(modelObject.getRegisteredDate().after(oneWeekAgo.getTime())){
				EmailFormatter.format(modelObject, plainTextSb, htmlTextSb);
			}
		}
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		System.out.println("ImageServlet.doPost()");
	}
}